package com.letchat.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.letchat.utils.JwtUtils;
import com.letchat.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("token");

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        // 排除 /subject/{id} 的 GET 请求
        if (requestURI.matches("/subject/\\d+") && "GET".equals(method)) {
            return true; // 不拦截
        }

        // 排除 /subject 的 GET 请求
        if ("/subject".equals(requestURI) && "GET".equals(method)) {
            return true; // 不拦截
        }

        if (jwt==null){
            response.getWriter().write(JSONObject.toJSONString(Result.error("NOT_LOGIN")));
            return false;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(JSONObject.toJSONString(Result.error("NOT_LOGIN")));
            return false;
        }

        return true;
    }
}
